<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="90px"
    >
      <el-form-item label="自习室名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入自习室名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:room:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:room:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:room:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="roomList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="80">
        <template slot-scope="scope">
          <span>{{
            (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="自习室ID" align="center" prop="id" v-if="false" />
      <el-table-column label="自习室名称" align="center" prop="name" />
      <el-table-column label="地点" align="center" prop="location" />
      <el-table-column label="封面" align="center" prop="cover" width="120">
        <template slot-scope="scope">
          <el-image
            style="width: 80px; height: 60px"
            :src="scope.row.cover"
            :preview-src-list="[scope.row.cover]"
            fit="cover"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column
        label="介绍"
        align="center"
        prop="introduction"
        width="120"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            style="color: #1890ff"
            @click="showIntroduction(scope.row.introduction)"
          >
            查看介绍
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="座位数" align="center" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.seatCount || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="是否收费"
        align="center"
        prop="isPaid"
        width="100"
      >
        <template slot-scope="scope">
          <el-tag :type="scope.row.isPaid === 1 ? 'danger' : 'success'">
            {{ scope.row.isPaid === 1 ? "收费" : "免费" }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        label="价格（元）"
        align="center"
        prop="price"
        width="100"
      >
        <template slot-scope="scope">
          <span>{{ Number(scope.row.price || 0).toFixed(2) }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="180"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:room:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:room:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改自习室对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="自习室名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入自习室名称" />
        </el-form-item>
        <el-form-item label="地点" prop="location">
          <el-input v-model="form.location" placeholder="请输入地点" />
        </el-form-item>
        <el-form-item label="封面" prop="cover">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeCoverUpload"
            :http-request="handleCoverUpload"
          >
            <img v-if="form.cover" :src="form.cover" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="是否收费" prop="isPaid">
          <el-radio-group v-model="form.isPaid">
            <el-radio :label="0">免费</el-radio>
            <el-radio :label="1">收费</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="价格（元）" prop="price" v-if="form.isPaid === 1">
          <el-input-number
            v-model="form.price"
            :min="0.01"
            :step="0.01"
            :precision="2"
            placeholder="请输入价格"
          />
        </el-form-item>

        <el-form-item label="介绍" prop="introduction">
          <el-input
            v-model="form.introduction"
            type="textarea"
            placeholder="请输入介绍"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRoomListAPI,
  getRoomInfoAPI,
  addRoomAPI,
  updateRoomAPI,
  deleteRoomAPI,
  uploadRoomCoverAPI,
  getRoomSeatsAPI,
} from "@/api/resource/room";

export default {
  name: "Room",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 自习室表格数据
      roomList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 当前自习室ID
      currentRoomId: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        location: undefined,
      },
      // 表单参数
      form: {
        id: undefined,
        name: undefined,
        location: undefined,
        cover: undefined,
        introduction: undefined,
        isPaid: 0,
        price: null,
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "自习室名称不能为空", trigger: "blur" },
          { max: 20, message: "长度不能超过20个字符", trigger: "blur" },
        ],
        location: [
          { required: true, message: "地点不能为空", trigger: "blur" },
          { max: 50, message: "长度不能超过50个字符", trigger: "blur" },
        ],
        cover: [{ required: true, message: "请上传封面图片", trigger: "blur" }],
        isPaid: [
          { required: true, message: "请选择是否收费", trigger: "change" },
        ],
        price: [
          { required: true, message: "请输入价格", trigger: "blur" },
          {
            type: "number",
            min: 0.01,
            message: "价格必须大于 0",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  watch: {
    "form.isPaid"(val) {
      if (val === 0) {
        this.form.price = 0;
      }
    },
  },

  methods: {
    /** 查询自习室列表 */
    getList() {
      this.loading = true;
      getRoomListAPI(this.queryParams).then(async (response) => {
        this.roomList = response.rows;
        this.total = response.total;

        // 获取每个自习室的座位数
        await this.getSeatCounts();

        this.loading = false;
      });
    },

    /** 获取所有自习室的座位数 */
    async getSeatCounts() {
      for (let room of this.roomList) {
        try {
          const res = await getRoomSeatsAPI(room.id);
          // 假设返回的是座位数组，计算长度
          this.$set(room, "seatCount", res.total || 0);
        } catch (error) {
          console.error(`获取自习室${room.id}座位数失败:`, error);
          this.$set(room, "seatCount", 0);
        }
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        location: undefined,
        cover: undefined,
        introduction: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加自习室";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0];
      getRoomInfoAPI(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改自习室";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 自动处理价格
          if (this.form.isPaid === 0) {
            this.form.price = 0;
          }
          if (this.form.id !== undefined) {
            updateRoomAPI(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRoomAPI(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id ? [row.id] : this.ids;
      this.$modal
        .confirm('是否确认删除自习室ID为"' + ids + '"的数据项？')
        .then(() => {
          return deleteRoomAPI(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 封面上传前校验 */
    beforeCoverUpload(file) {
      const isImage = file.type.startsWith("image/");
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (!isImage) {
        this.$message.error("只能上传图片文件!");
        return false;
      }
      if (!isLt1M) {
        this.$message.error("上传图片大小不能超过 1MB!");
        return false;
      }
      return true;
    },

    /** 封面上传处理 */
    handleCoverUpload(file) {
      const formData = new FormData();
      formData.append("file", file.file);

      uploadRoomCoverAPI(formData)
        .then((response) => {
          // 获取当前页面基础URL
          const baseUrl = window.location.origin;

          // 处理URL路径
          let imageUrl = response.url; // 获取返回的路径
          if (!imageUrl.startsWith("http")) {
            // 如果是相对路径，拼接完整URL
            imageUrl = `${baseUrl}${
              imageUrl.startsWith("/") ? "" : "/"
            }${imageUrl}`;
          }

          // 保存完整URL到数据库
          this.form.cover = imageUrl;
          this.$message.success(response.msg || "上传成功");
        })
        .catch((error) => {
          console.error("上传错误:", error);
          this.$message.error(error.message || "上传失败");
        });
    },
    /** 显示自习室介绍 */
    showIntroduction(intro) {
      this.$alert(intro, "自习室介绍", {
        confirmButtonText: "确定",
        customClass: "intro-dialog",
        dangerouslyUseHTMLString: true,
      });
    },
  },
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}

.intro-dialog {
  width: 60%;
  max-width: 800px;
}

.intro-dialog .el-message-box__content {
  max-height: 60vh;
  overflow-y: auto;
  white-space: pre-wrap;
  word-break: break-word;
}
</style>
